package com.wanshi.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wanshi.member.base.Page;
import com.wanshi.member.base.Result;
import com.wanshi.member.entity.Staff;
import com.wanshi.member.entity.Supplier;
import com.wanshi.member.mapper.StaffMapper;
import com.wanshi.member.req.MemberREQ;
import com.wanshi.member.req.PasswordREQ;
import com.wanshi.member.req.StaffREQ;
import com.wanshi.member.service.IStaffService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanshi.member.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 员工信息表 服务实现类
 * </p>
 *
 * @author 顽石教育-www.wanshi.com
 * @since 2021-05-08
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Result login(String username, String password) {
        //获取用户名密码  判断是否村存在

        //2 存在,调用JWTUtils 生成token
        Result error = Result.error("用户名或密码错误");

        if (StringUtils.isBlank(username)
                || StringUtils.isBlank(password)) {
            return error;
        }

        // 1. 通过用户名查询数据
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        Staff staff = baseMapper.selectOne(wrapper);
        // 用户不存在
        if (staff == null) {
            return error;
        }

        // 2. 存在，判断输入的密码和数据库密码是否一致
        boolean b = new BCryptPasswordEncoder().matches(password, staff.getPassword());
        if (!b) {
            return error;
        }

        // 3. 生成 token
        String jwt =
                jwtUtil.createJWT(staff.getId() + "", staff.getUsername(), true);
        // 4. 响应给客户端
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return Result.ok(map);
    }

    @Override
    public Result getUserInfo(String token) {
        // 解析令牌
        Claims claims = jwtUtil.parseJWT(token);
        // 解析不到，或则用户名为空时，提供获取失败
        if (claims == null ||
                StringUtils.isBlank(claims.getSubject())) {
            return Result.error("获取用户令牌失败");
        }

        // 获取用户名
        String username = claims.getSubject();

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        Staff staff = baseMapper.selectOne(wrapper);
        if (staff == null) {
            return Result.error("用户不存在");
        }

        // 将密码设置null,为了安全
        staff.setPassword(null);

        return Result.ok(staff);
    }

    @Override
    public Result search(long page, long size, StaffREQ req) {
        // 封装查询条件
        QueryWrapper<Staff> query = new QueryWrapper();
        if (req != null) {
            if (StringUtils.isNotBlank(req.getUsername())) {
                query.like("username", req.getUsername());
            }
            if (StringUtils.isNotBlank(req.getName())) {
                query.like("name", req.getName());
            }
        }

        query.orderByDesc("id");
        // 分页查询列表数据
        IPage<Staff> data =
                baseMapper.selectPage(new Page<Staff>(page, size), query);
        return Result.ok(data);
    }


    @Override
    public Result checkPassword(PasswordREQ req) {
        if(req == null || StringUtils.isEmpty(req.getPassword())) {
            return Result.error("原密码不能为空");
        }

        // 通过用户id查询用户信息（正确密码）
        Staff staff = baseMapper.selectById(req.getUserId());
        // 判断输入的密码是否正确
        boolean b = new BCryptPasswordEncoder().matches(req.getPassword(), staff.getPassword());
        if(b) {
            return Result.ok();
        }
        return Result.error("原密码错误");
    }

    @Override
    public Result updatePassword(PasswordREQ req) {
        if(req == null || StringUtils.isEmpty(req.getPassword())) {
            return Result.error("新密码不能为空");
        }

        // 将新密码加密
        String password =
                new BCryptPasswordEncoder().encode(req.getPassword());

        // 更新操作
        Staff staff = baseMapper.selectById(req.getUserId());
        staff.setPassword(password);
        baseMapper.updateById(staff);
        return Result.ok();
    }
}
